package com.ruoyi.student.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.dictionaries.domain.Regions;
import com.ruoyi.dictionaries.service.IRegionsService;
import com.ruoyi.student.utils.importUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.student.domain.StudentInfoImport;
import com.ruoyi.student.service.IStudentInfoImportService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入学前学生信息导入Controller
 *
 * @author gdslovehy
 * @date 2025-06-20
 */
@RestController
@RequestMapping("/student/import")
public class StudentInfoImportController extends BaseController
{
    @Autowired
    private IStudentInfoImportService studentInfoImportService;
    @Autowired
    private IRegionsService regionsService;
    /**
     * 查询入学前学生信息导入列表
     */
    //@PreAuthorize("@ss.hasPermi('student:import:list')")
    @GetMapping("/list")
    public TableDataInfo list(StudentInfoImport studentInfoImport)
    {
        startPage();
        List<StudentInfoImport> list = studentInfoImportService.selectStudentInfoImportList(studentInfoImport);
        return getDataTable(list);
    }

    /**
     * 导出入学前学生信息导入列表
     */
/*    @PreAuthorize("@ss.hasPermi('student:import:export')")*/
    @Log(title = "入学前学生信息导入", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentInfoImport studentInfoImport)
    {
        List<StudentInfoImport> list = studentInfoImportService.selectStudentInfoImportList(studentInfoImport);
        ExcelUtil<StudentInfoImport> util = new ExcelUtil<StudentInfoImport>(StudentInfoImport.class);
        util.exportExcel(response, list, "入学前学生信息导入数据");
    }

    /**
     * 获取入学前学生信息导入详细信息
     */
    @PreAuthorize("@ss.hasPermi('student:import:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(studentInfoImportService.selectStudentInfoImportById(id));
    }

    /**
     * 新增入学前学生信息导入
     */
/*    @PreAuthorize("@ss.hasPermi('student:import:add')")*/
    @Log(title = "入学前学生信息导入", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StudentInfoImport studentInfoImport)
    {
        studentInfoImport.setId(IdUtils.fastSimpleUUID());
        return toAjax(studentInfoImportService.insertStudentInfoImport(studentInfoImport));
    }

    /**
     * 修改入学前学生信息导入
     */
/*    @PreAuthorize("@ss.hasPermi('student:import:edit')")*/
    @Log(title = "入学前学生信息导入", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StudentInfoImport studentInfoImport)
    {
        return toAjax(studentInfoImportService.updateStudentInfoImport(studentInfoImport));
    }
/*    @PreAuthorize("@ss.hasPermi('student:import:add')")*/
    @Log(title = "入学前学生信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult excelImport(MultipartFile file) throws Exception {
        ExcelUtil<StudentInfoImport> util = new ExcelUtil<StudentInfoImport>(StudentInfoImport.class);
        List<StudentInfoImport> skuList = util.importExcel(file.getInputStream());

        // 1. 生成ID（保持原有逻辑）
        for (StudentInfoImport studentInfoImport : skuList) {
            studentInfoImport.setId(IdUtils.fastSimpleUUID());
        }

        // 2. 数据预处理（保持原有逻辑）
        Regions region = new Regions();
        List<Regions> regionList = regionsService.selectRegionsList(region);
        importUtils.getRegion(skuList, regionList);
        importUtils.getCard(skuList);
        importUtils.getXh(skuList);
        importUtils.getBirthDateFromIdCard(skuList);
        importUtils.getByny(skuList);
        importUtils.getRwqrxny(skuList);
        importUtils.getRwny(skuList);
        importUtils.getTyny(skuList);
        for (StudentInfoImport studentInfoImport : skuList) {
            if(studentInfoImport.getJyzt() == null){
                studentInfoImport.setDrzt("1");
            }else {
                studentInfoImport.setDrzt("2");
            }
        }
        // 3. 核心：查重逻辑（通过唯一标识“学号xh”判断）
        // 3.1 查询数据库中已存在的所有学号，存入Set（高效判断）
        Set<String> existingXhSet = studentInfoImportService.selectAllExistingXh();
        // 3.2 分离“新记录”和“重复记录”
        List<StudentInfoImport> newRecords = new ArrayList<>();
        List<String> duplicateXhList = new ArrayList<>();
        for (StudentInfoImport importData : skuList) {
            String xh = importData.getXh(); // 假设xh（学号）是唯一标识
            if (xh == null || xh.trim().isEmpty()) {
                // 过滤学号为空的无效数据
                continue;
            }
            if (existingXhSet.contains(xh.trim())) {
                // 已存在，记录重复学号
                duplicateXhList.add(xh);
            } else {
                // 新记录，加入待插入列表
                newRecords.add(importData);
                // 将新学号加入“已存在”集合（避免同Excel中重复的情况）
                existingXhSet.add(xh.trim());
            }
        }

        // 4. 执行插入（只插入新记录）
        int insertCount = 0;
        if (!newRecords.isEmpty()) {
            insertCount = studentInfoImportService.insertstudents(newRecords);
        }

        // 5. 构建返回结果（包含重复信息）
        StringBuilder resultMsg = new StringBuilder();
        resultMsg.append("导入成功：").append(insertCount).append("条；");
        if (!duplicateXhList.isEmpty()) {
            resultMsg.append("重复跳过：").append(duplicateXhList.size()).append("条（学号：")
                    .append(String.join(",", duplicateXhList.subList(0, Math.min(5, duplicateXhList.size()))))
                    .append(duplicateXhList.size() > 5 ? "..." : "").append("）");
        }

        return AjaxResult.success(resultMsg.toString())
                .put("insertCount", insertCount)
                .put("duplicateCount", duplicateXhList.size())
                .put("duplicateXh", duplicateXhList);
    }
    /**
     * 删除入学前学生信息导入
     */
/*    @PreAuthorize("@ss.hasPermi('student:import:remove')")*/
    @Log(title = "入学前学生信息导入", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(studentInfoImportService.deleteStudentInfoImportByIds(ids));
    }
}
